package com.gzc.just.play.last.war.centralserver.handler;



import com.gzc.just.play.last.war.common.handler.SimpleMessageHandler;

import com.gzc.just.play.last.war.centralserver.service.UserStatusService;

import io.netty.channel.ChannelHandlerContext;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Component;



import java.util.Map;



/**

 * 鐢ㄦ埛娑堟伅澶勭悊鍣

 * 澶勭悊鐢ㄦ埛鐩稿叧鐨勬秷鎭锛屽傝幏鍙栫敤鎴蜂俊鎭銆佹洿鏂扮敤鎴风姸鎬佺瓑

 */

@Component("central-userMessageHandler")
public class UserMessageHandler implements SimpleMessageHandler {

    private static final Logger logger = LoggerFactory.getLogger(UserMessageHandler.class);

    

    @Autowired

    private UserStatusService userService;

    

    private static final int USER_MESSAGE = 3002;

    

    @Override

    public void handle(Object message, ChannelHandlerContext ctx) throws Exception {

        // 浠庝笂涓嬫枃涓鑾峰彇鐜╁禝D

        io.netty.util.AttributeKey<Long> playerIdKey = io.netty.util.AttributeKey.valueOf("playerId");

        Long playerId = ctx.channel().attr(playerIdKey).get();

        if (playerId == null) {

            logger.error("Player ID not found in context, cannot process user message");

            return;

        }

        

        // 浠庢秷鎭涓瑙ｆ瀽鎿嶄綔绫诲瀷

        String operation = extractOperation(message);

        

        switch (operation) {

            case "getUserInfo":

                handleGetUserInfo(playerId, ctx);

                break;

            case "updateUserStatus":

                handleUpdateUserStatus(playerId, message, ctx);

                break;

            case "getOnlineFriends":

                handleGetOnlineFriends(playerId, ctx);

                break;

            default:

                logger.warn("Unknown user operation: {}", operation);

                break;

        }

    }

    

    /**

     * 澶勭悊鑾峰彇鐢ㄦ埛淇℃伅璇锋眰

     */

    private void handleGetUserInfo(Long playerId, ChannelHandlerContext ctx) {

        // 鑾峰彇鐢ㄦ埛淇℃伅

        Map<String, Object> userInfo = userService.getUserInfo(playerId);

        

        // 鍙戦佺敤鎴蜂俊鎭鍝嶅簲

        if (userInfo != null) {

            sendUserInfoResponse(ctx, userInfo, true, "User info retrieved successfully");

            logger.info("Retrieved info for user: {}", playerId);

        } else {

            sendUserInfoResponse(ctx, null, false, "User not found: " + playerId);

            logger.warn("User not found: {}", playerId);

        }

    }

    

    /**

     * 澶勭悊鏇存柊鐢ㄦ埛鐘舵佽锋眰

     */

    private void handleUpdateUserStatus(Long playerId, Object message, ChannelHandlerContext ctx) {

        // 浠庢秷鎭涓瑙ｆ瀽鐘舵佷俊鎭

        Map<String, Object> statusInfo = extractStatusInfo(message);

        

        // 鏇存柊鐢ㄦ埛鐘舵

        if (userService.updateUserStatus(playerId, statusInfo)) {

            sendUpdateStatusResponse(ctx, true, "User status updated successfully");

            logger.info("Updated status for user: {}", playerId);

        } else {

            sendUpdateStatusResponse(ctx, false, "Failed to update user status");

            logger.warn("Failed to update status for user: {}", playerId);

        }

    }

    

    /**

     * 澶勭悊鑾峰彇鍦ㄧ嚎濂藉弸璇锋眰

     */

    private void handleGetOnlineFriends(Long playerId, ChannelHandlerContext ctx) {

        // 鑾峰彇鍦ㄧ嚎濂藉弸鍒楄〃

        Map<Long, Map<String, Object>> onlineFriends = userService.getOnlineFriends(playerId);

        

        // 鍙戦佸湪绾垮ソ鍙嬪垪琛ㄥ搷搴

        sendOnlineFriendsResponse(ctx, onlineFriends, true, "Online friends retrieved successfully");

        logger.info("Retrieved {} online friends for user: {}", onlineFriends.size(), playerId);

    }

    

    private String extractOperation(Object message) {

        // 瀹為檯瀹炵幇涓搴旇ヤ粠娑堟伅瀵硅薄涓瑙ｆ瀽鎿嶄綔绫诲瀷

        // 杩欓噷杩斿洖绀轰緥鍊

        return "getUserInfo";

    }

    

    private Map<String, Object> extractStatusInfo(Object message) {

        // 瀹為檯瀹炵幇涓搴旇ヤ粠娑堟伅瀵硅薄涓瑙ｆ瀽鐘舵佷俊鎭

        // 杩欓噷杩斿洖绀轰緥鍊

        return Map.of(

            "status", "online",

            "location", "lobby",

            "gameMode", "normal"

        );

    }

    

    private void sendUserInfoResponse(ChannelHandlerContext ctx, Map<String, Object> userInfo, 

                                     boolean success, String message) {

        // 瀹為檯瀹炵幇涓搴旇ユ瀯閫犲苟鍙戦佺敤鎴蜂俊鎭鍝嶅簲娑堟伅

        logger.info("Sending user info response: success={}, message={}", success, message);

        

        // 绀轰緥锛氭墦鍗扮敤鎴蜂俊鎭鍐呭癸紙瀹為檯瀹炵幇涓搴旇ュ皢淇℃伅搴忓垪鍖栦负鍝嶅簲娑堟伅锛

        if (success && userInfo != null) {

            logger.debug("User info content:");

            for (Map.Entry<String, Object> entry : userInfo.entrySet()) {

                logger.debug("{}: {}", entry.getKey(), entry.getValue());

            }

        }

    }

    

    private void sendUpdateStatusResponse(ChannelHandlerContext ctx, boolean success, String message) {

        // 瀹為檯瀹炵幇涓搴旇ユ瀯閫犲苟鍙戦佹洿鏂扮姸鎬佸搷搴旀秷鎭

        logger.info("Sending update status response: success={}, message={}", success, message);

    }

    

    private void sendOnlineFriendsResponse(ChannelHandlerContext ctx, Map<Long, Map<String, Object>> onlineFriends, 

                                         boolean success, String message) {

        // 瀹為檯瀹炵幇涓搴旇ユ瀯閫犲苟鍙戦佸湪绾垮ソ鍙嬪搷搴旀秷鎭

        logger.info("Sending online friends response: success={}, message={}, friendCount={}", 

                   success, message, onlineFriends.size());

        

        // 绀轰緥锛氭墦鍗板湪绾垮ソ鍙嬪唴瀹癸紙瀹為檯瀹炵幇涓搴旇ュ皢鍒楄〃搴忓垪鍖栦负鍝嶅簲娑堟伅锛

        if (success && !onlineFriends.isEmpty()) {

            logger.debug("Online friends content:");

            for (Map.Entry<Long, Map<String, Object>> entry : onlineFriends.entrySet()) {

                logger.debug("Friend ID: {}, Info: {}", entry.getKey(), entry.getValue());

            }

        }

    }



    @Override

    public int getMessageId() {

        return USER_MESSAGE;

    }

    

    @Override

    public String getName() {

        return "UserMessageHandler";

    }

    

    @Override

    public Logger getLogger() {

        return logger;

    }

}